package io.gitee.zhangbinhub.acp.cloud.resource.server.error

import io.gitee.zhangbinhub.acp.boot.exceptions.AcpWebExceptionHandler
import io.gitee.zhangbinhub.acp.boot.exceptions.ErrorResult
import io.gitee.zhangbinhub.acp.boot.tools.PackageTools
import org.springframework.core.Ordered
import org.springframework.http.HttpStatus
import org.springframework.security.access.AccessDeniedException
import org.springframework.security.core.AuthenticationException

class AcpWebSecurityErrorHandler : AcpWebExceptionHandler {
    override fun getOrder(): Int = Ordered.LOWEST_PRECEDENCE - 1
    override fun identify(ex: Throwable?): Boolean = ex is AccessDeniedException || ex is AuthenticationException
    override fun handle(ex: Throwable?): ErrorResult = when (ex) {
        // security
        is AccessDeniedException -> {
            PackageTools.buildErrorResult(HttpStatus.FORBIDDEN, "权限不足")
        }

        is AuthenticationException -> {
            PackageTools.buildErrorResult(HttpStatus.UNAUTHORIZED, "权限验证失败")
        }

        else -> {
            PackageTools.buildErrorResult(HttpStatus.INTERNAL_SERVER_ERROR, ex?.message)
        }
    }
}